const jwt = require('jsonwebtoken');
const helper = require('../../util/helper');
const config = require('../../config/environment/index');
const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const common = require('../../core/common');
const stringUtils = require('../../core/util/StringUtils');
const assign = require('lodash/assign');

/*
 request {
 room_id: 1,
 room_name:'红外感应器'，
 vendor：'鸿雁'，
 }
 */
exports.add = async (ctx) => {
    let area = ctx.request.body.area || 0;
    let room_name = ctx.request.body.room_name ? ctx.request.body.room_name.trim() : '';
    let house_type_id = ctx.params.house_type_id || 0;
    let create_time = moment().format('YYYY-MM-DD HH:mm:ss');
    let update_time = moment().format('YYYY-MM-DD HH:mm:ss');

    try {
        if ( parseInt(house_type_id) <= 0 || room_name === '') {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return;
        }
        let newroom = {
            area,
            house_type_id,
            room_name,
            update_time,
            create_time,
        };
        let selectHouseTypes = await mysql.query(`select * from house_type where house_type_id = ? `, house_type_id);
        if (selectHouseTypes.length <= 0) {
            ctx.body = {
                result: 202,
                message: "户型不存在或已删除"
            };
            return;
        }
        let selectExistRooms = await mysql.query(`select * from room where house_type_id = ? and room_name = ? `,[house_type_id,room_name]);
        if (selectExistRooms.length > 0){
            ctx.body = {
                result: 203,
                message: "该户型下已有此房间"
            };
            return;
        }
        await new Promise((resolve, reject) => {
            var trans = mysql.Client.startTransaction();
            trans.query(`INSERT INTO room SET ?`, newroom, function (err, info) {
                if (err || info.affectedRows <= 0) {
                    trans.rollback();
                    ctx.body = {
                        result: 204,
                        message: "新增room失败" + err.toString()
                    };
                    resolve(ctx);
                } else {
                    selectHouseTypes[0].room_num++;
                    trans.query(`UPDATE house_type SET ? WHERE house_type_id = ? `, [selectHouseTypes[0], house_type_id], function (err, resultUpdate) {
                        if (err || resultUpdate.affectedRows <= 0) {
                            trans.rollback();
                            ctx.body = {
                                result: 204,
                                message: "新增room失败" + err.toString()
                            };
                            resolve(ctx);
                        } else {
                            trans.commit();
                            ctx.body = {
                                result: 200,
                                message: "新增room成功"
                            };
                            resolve(ctx);
                        }
                    });
                }
            });
            trans.execute();
        });
    } catch (error) {
        ctx.body = {
            result: 205,
            message: '错误' + error.toString(),
        };
    }
}

exports.getList = async (ctx) => {
    let params = ctx.query;
    let counts = params.counts || 10;
    let indexfrom = params.indexfrom || 0;
    let house_type_id = ctx.params.house_type_id;

    try {
        let results;
        let totalResult;
        if (house_type_id) {
            results = await mysql.query(`SELECT * FROM room WHERE house_type_id =${house_type_id} ORDER BY room_id DESC LIMIT ${indexfrom}, ${counts} `);
            totalResult = await mysql.query(`SELECT COUNT(room_id) AS total FROM room WHERE house_type_id =${house_type_id} `);
        } else {
            results = await mysql.query(`SELECT * FROM room ORDER BY room_id DESC LIMIT ${indexfrom}, ${counts} `);
            totalResult = await mysql.query(`SELECT COUNT(room_id) AS total FROM room `);
        }

        ctx.body = {
            result: 200,
            list: results,
            totalpage:Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0)/counts),
            totalcounts:totalResult.length > 0 ? totalResult[0].total : 0,
            message: "查询成功"
        };
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"
        };
    }
}

exports.update = async (ctx) => {
    let room_id = ctx.request.body.room_id || 0;
    let room_name = ctx.request.body.room_name ? ctx.request.body.room_name.trim() : '';
    let update_time = moment().format('YYYY-MM-DD HH:mm:ss');
    try {
        if (parseInt(room_id) <= 0 || room_name === '') {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return;
        }
        let selectRows = await mysql.query(`SELECT * FROM room WHERE room_id = ?`, room_id);
        if (selectRows.length > 0) {
            let selectExistRooms = await mysql.query(`select * from room where house_type_id = ? and room_name = ? and room_id <> ? `,[selectRows[0].house_type_id,room_name,room_id]);
            if (selectExistRooms.length > 0){
                ctx.body = {
                    result: 203,
                    message: "该户型下已有此房间"
                };
                return;
            }
            let update_date = assign({}, selectRows[0], ctx.request.body, {update_time});
            let ret = await mysql.query(`UPDATE room SET ? WHERE room_id = ${room_id}`, update_date);
            if (!ret || ret.insertId === -1) {
                ctx.body = {
                    result: 202,
                    message: "更新失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    message: "更新成功"
                };
            }
        } else {
            ctx.body = {
                result: 203,
                message: "对象不存在或者已删除"
            };
        }
    } catch (e) {
        ctx.body = {
            result: 204,
            message: "更新失败" + e.toString()
        };
    }

}

exports.delete = async (ctx) => {
    let room_id = ctx.params.room_id || 0;

    try {
        if (parseInt(room_id) <= 0) {
            ctx.body = {
                result: 201,
                message: "无效的room_id"
            };
            return;
        }
        let selectRooms = await mysql.query(`select * from room where room_id = ? `, room_id);
        if (selectRooms.length <= 0) {
            ctx.body = {
                result: 202,
                message: "房间不存在或已删除"
            };
            return;
        }
        let selectHouseTypes = await mysql.query(`select * from house_type where house_type_id = ? `, selectRooms[0].house_type_id);
        if (selectHouseTypes.length <= 0) {
            ctx.body = {
                result: 202,
                message: "户型不存在或已删除"
            };
            return;
        }

        await new Promise((resolve, reject) => {
            var trans = mysql.Client.startTransaction();
            trans.query(`delete  from room  WHERE room_id = ${room_id}`, function (err, info) {
                if (err || info.affectedRows <= 0) {
                    trans.rollback();
                    ctx.body = {
                        result: 203,
                        message: "删除room失败" + err.toString()
                    };
                    resolve(ctx);
                } else {
                    selectHouseTypes[0].room_num--;
                    trans.query(`UPDATE house_type SET ? WHERE house_type_id = ? `, [selectHouseTypes[0], selectRooms[0].house_type_id], function (err, resultUpdate) {
                        if (err || resultUpdate.affectedRows <= 0) {
                            trans.rollback();
                            ctx.body = {
                                result: 204,
                                message: "删除room失败" + err.toString()
                            };
                            resolve(ctx);
                        } else {
                            trans.commit();
                            ctx.body = {
                                result: 200,
                                message: "删除room成功"
                            };
                            resolve(ctx);
                        }
                    });
                }
            });
            trans.execute();
        });
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}

exports.getDetail = async (ctx) => {
    let room_id = ctx.params.room_id;

    try {
        if (parseInt(room_id) <= 0) {
            ctx.body = {
                result: 201,
                message: "无效的room_id"
            };
            return;
        }
        let selectRooms = await mysql.query(`SELECT * FROM room where room_id = ${room_id}`);
        if (selectRooms.length > 0) {
            let selectHouseType = await mysql.query(`SELECT * FROM house_type where house_type_id = ${selectRooms[0].house_type_id}`);
            roomResult = selectRooms[0];
            roomResult.house_type_name = (selectHouseType.length > 0) ? selectHouseType[0].house_type_name : null;
            selectScenarios = await mysql.query(`SELECT * FROM scenario where room_id = ${room_id} and is_deleted = 0 `);
            for (let scenario of Object.values(selectScenarios)) {
                let scenarioDevices = await mysql.query(`SELECT * FROM t_scenario_v_device WHERE scenario_id = ${scenario.scenario_id} `);
                scenario.triggering_condition = [];
                scenario.matching_condition = [];
                scenario.action = [];
                for (let scenarioDevice of Object.values(scenarioDevices)) {
                    if (scenarioDevice.type === 0) {
                        scenario.triggering_condition.push(scenarioDevice);
                    } else if (scenarioDevice.type === 1) {
                        scenario.matching_condition.push(scenarioDevice);
                    } else {
                        scenario.action.push(scenarioDevice);
                    }
                }
            }
            selectProducts = await mysql.query(`SELECT product_id,product_name,vendor_name,model_type_name,pic_url,model_name,tag AS link FROM v_temp_device_detail where room_id = ${room_id}`);
            roomResult.device_count = selectProducts.length;
            roomResult.scenario_list = selectScenarios;
            roomResult.device_list = selectProducts;
            ctx.body = {
                result: 200,
                resultInfo: roomResult,
                message: "查询成功"
            };
        } else {
            ctx.body = {
                result: 202,
                message: "查询失败"
            };
        }

    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}

